/*
 * addUserWithPasswordMenu.java
 *
 * Created on __DATE__, __TIME__
 */

package serverPresentation;

import java.awt.Image;
import java.awt.Toolkit;
import java.security.PublicKey;

import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import connection.CitizenCardInterface;
import connection.DatabaseConnection;
import connection.exception.CardErrorException;

import security.Hash;
import security.crypto.AssimEncryption;
import server.ServerData;
import utils.Base64Processing;

/**
 *
 * @author  __USER__
 */
public class AddUserWithPasswordMenu extends javax.swing.JFrame {

	private static final long serialVersionUID = 1L;

	/** Creates new form addUserWithPasswordMenu */
	public AddUserWithPasswordMenu() {
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (UnsupportedLookAndFeelException e) {
			e.printStackTrace();
		}

		initComponents();

		Image im = Toolkit.getDefaultToolkit().getImage(
		"images/security-icon.gif");
		this.setIconImage(im);
	}

	/** This method is called from within the constructor to
	 * initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is
	 * always regenerated by the Form Editor.
	 */
	//GEN-BEGIN:initComponents
	// <editor-fold defaultstate="collapsed" desc="Generated Code">
	private void initComponents() {

		jLabel1 = new javax.swing.JLabel();
		jLabel2 = new javax.swing.JLabel();
		jLabel3 = new javax.swing.JLabel();
		jLabel4 = new javax.swing.JLabel();
		jLabel5 = new javax.swing.JLabel();
		_ccCertificateIncluded = new javax.swing.JCheckBox();
		_cancelButton = new javax.swing.JButton();
		_nextButton = new javax.swing.JButton();
		_firstNameBox = new javax.swing.JTextField();
		_lastNameBox = new javax.swing.JTextField();
		_addressBox = new javax.swing.JTextField();
		jLabel6 = new javax.swing.JLabel();
		_usernameBox = new javax.swing.JTextField();
		_passwordBox = new javax.swing.JPasswordField();
		_passwordConfBox = new javax.swing.JPasswordField();

		setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
		setTitle("Adicionar Utilizador com Password");

		jLabel1.setText("Primeiro Nome");

		jLabel2.setText("Apelido (Apenas \u00faltimo)");

		jLabel3.setText("Morada");

		jLabel4.setText("Palavra-Passe");

		jLabel5.setText("Confirme Palavra-Passe");

		_ccCertificateIncluded
		.setText("Incluir Certificado de Cart\u00e3o do Cidad\u00e3o?");

		_cancelButton.setText("Cancelar");
		_cancelButton.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				cancelButtonMouseClicked(evt);
			}
		});

		_nextButton.setText("Continuar >");
		_nextButton.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				nextButtonMouseClicked(evt);
			}
		});

		jLabel6.setText("Nome de Utilizador");

		_passwordBox.setText("jPasswordField1");

		_passwordConfBox.setText("jPasswordField2");

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
				getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
						.addContainerGap()
						.addGroup(
								layout.createParallelGroup(
										javax.swing.GroupLayout.Alignment.LEADING)
										.addGroup(
												layout.createSequentialGroup()
												.addGroup(
														layout.createParallelGroup(
																javax.swing.GroupLayout.Alignment.LEADING)
																.addGroup(
																		javax.swing.GroupLayout.Alignment.TRAILING,
																		layout.createSequentialGroup()
																		.addComponent(
																				_nextButton)
																				.addPreferredGap(
																						javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																						.addComponent(
																								_cancelButton))
																								.addGroup(
																										layout.createSequentialGroup()
																										.addGroup(
																												layout.createParallelGroup(
																														javax.swing.GroupLayout.Alignment.LEADING)
																														.addComponent(
																																jLabel1)
																																.addComponent(
																																		jLabel2)
																																		.addComponent(
																																				jLabel3)
																																				.addComponent(
																																						jLabel6)
																																						.addComponent(
																																								jLabel4))
																																								.addGap(7,
																																										7,
																																										7)
																																										.addGroup(
																																												layout.createParallelGroup(
																																														javax.swing.GroupLayout.Alignment.TRAILING)
																																														.addComponent(
																																																_passwordBox,
																																																javax.swing.GroupLayout.Alignment.LEADING,
																																																javax.swing.GroupLayout.DEFAULT_SIZE,
																																																136,
																																																Short.MAX_VALUE)
																																																.addComponent(
																																																		_usernameBox,
																																																		javax.swing.GroupLayout.Alignment.LEADING,
																																																		javax.swing.GroupLayout.DEFAULT_SIZE,
																																																		136,
																																																		Short.MAX_VALUE)
																																																		.addComponent(
																																																				_addressBox,
																																																				javax.swing.GroupLayout.Alignment.LEADING,
																																																				javax.swing.GroupLayout.DEFAULT_SIZE,
																																																				136,
																																																				Short.MAX_VALUE)
																																																				.addComponent(
																																																						_lastNameBox,
																																																						javax.swing.GroupLayout.DEFAULT_SIZE,
																																																						136,
																																																						Short.MAX_VALUE)
																																																						.addGroup(
																																																								javax.swing.GroupLayout.Alignment.LEADING,
																																																								layout.createSequentialGroup()
																																																								.addPreferredGap(
																																																										javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
																																																										.addComponent(
																																																												_passwordConfBox,
																																																												javax.swing.GroupLayout.DEFAULT_SIZE,
																																																												136,
																																																												Short.MAX_VALUE))
																																																												.addComponent(
																																																														_firstNameBox,
																																																														javax.swing.GroupLayout.Alignment.LEADING,
																																																														javax.swing.GroupLayout.PREFERRED_SIZE,
																																																														136,
																																																														javax.swing.GroupLayout.PREFERRED_SIZE))
																																																														.addGap(44,
																																																																44,
																																																																44))
																																																																.addComponent(
																																																																		jLabel5))
																																																																		.addContainerGap())
																																																																		.addGroup(
																																																																				layout.createSequentialGroup()
																																																																				.addComponent(
																																																																						_ccCertificateIncluded)
																																																																						.addContainerGap(
																																																																								85,
																																																																								Short.MAX_VALUE)))));
		layout.setVerticalGroup(layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
						.addContainerGap()
						.addGroup(
								layout.createParallelGroup(
										javax.swing.GroupLayout.Alignment.BASELINE)
										.addComponent(jLabel1)
										.addComponent(
												_firstNameBox,
												javax.swing.GroupLayout.PREFERRED_SIZE,
												javax.swing.GroupLayout.DEFAULT_SIZE,
												javax.swing.GroupLayout.PREFERRED_SIZE))
												.addPreferredGap(
														javax.swing.LayoutStyle.ComponentPlacement.RELATED)
														.addGroup(
																layout.createParallelGroup(
																		javax.swing.GroupLayout.Alignment.BASELINE)
																		.addComponent(jLabel2)
																		.addComponent(
																				_lastNameBox,
																				javax.swing.GroupLayout.PREFERRED_SIZE,
																				javax.swing.GroupLayout.DEFAULT_SIZE,
																				javax.swing.GroupLayout.PREFERRED_SIZE))
																				.addPreferredGap(
																						javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																						.addGroup(
																								layout.createParallelGroup(
																										javax.swing.GroupLayout.Alignment.BASELINE)
																										.addComponent(jLabel3)
																										.addComponent(
																												_addressBox,
																												javax.swing.GroupLayout.PREFERRED_SIZE,
																												javax.swing.GroupLayout.DEFAULT_SIZE,
																												javax.swing.GroupLayout.PREFERRED_SIZE))
																												.addPreferredGap(
																														javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																														.addGroup(
																																layout.createParallelGroup(
																																		javax.swing.GroupLayout.Alignment.BASELINE)
																																		.addComponent(jLabel6)
																																		.addComponent(
																																				_usernameBox,
																																				javax.swing.GroupLayout.PREFERRED_SIZE,
																																				javax.swing.GroupLayout.DEFAULT_SIZE,
																																				javax.swing.GroupLayout.PREFERRED_SIZE))
																																				.addGap(6, 6, 6)
																																				.addGroup(
																																						layout.createParallelGroup(
																																								javax.swing.GroupLayout.Alignment.BASELINE)
																																								.addComponent(jLabel4)
																																								.addComponent(
																																										_passwordBox,
																																										javax.swing.GroupLayout.PREFERRED_SIZE,
																																										javax.swing.GroupLayout.DEFAULT_SIZE,
																																										javax.swing.GroupLayout.PREFERRED_SIZE))
																																										.addPreferredGap(
																																												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																																												.addGroup(
																																														layout.createParallelGroup(
																																																javax.swing.GroupLayout.Alignment.BASELINE)
																																																.addComponent(jLabel5)
																																																.addComponent(
																																																		_passwordConfBox,
																																																		javax.swing.GroupLayout.PREFERRED_SIZE,
																																																		javax.swing.GroupLayout.DEFAULT_SIZE,
																																																		javax.swing.GroupLayout.PREFERRED_SIZE))
																																																		.addPreferredGap(
																																																				javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																																																				.addComponent(_ccCertificateIncluded)
																																																				.addPreferredGap(
																																																						javax.swing.LayoutStyle.ComponentPlacement.RELATED,
																																																						20, Short.MAX_VALUE)
																																																						.addGroup(
																																																								layout.createParallelGroup(
																																																										javax.swing.GroupLayout.Alignment.BASELINE)
																																																										.addComponent(_cancelButton)
																																																										.addComponent(_nextButton))
																																																										.addContainerGap()));

		pack();
	}// </editor-fold>
	//GEN-END:initComponents

	private void nextButtonMouseClicked(java.awt.event.MouseEvent evt) {
		String firstName = _firstNameBox.getText();
		String lastName = _lastNameBox.getText();
		String address = _addressBox.getText();
		String username = _usernameBox.getText();
		String password = new String(_passwordBox.getPassword());
		String passwordConf = new String(_passwordConfBox.getPassword());
		boolean certificateChecked = _ccCertificateIncluded.isSelected();

		if(firstName.isEmpty()||lastName.isEmpty()||address.isEmpty()||username.isEmpty()|| password.isEmpty()||passwordConf.isEmpty()){
			JOptionPane.showMessageDialog(this, "Todos os campos têm de ser preenchidos!!");
			return;
		}

		if(!password.equals(passwordConf)){
			JOptionPane.showMessageDialog(this, "A Palavra-Passe introduzida e a confirmação não são iguais!!");
			return;
		}

		String certificate = null;
		if(certificateChecked){
			try {			

				certificate = Base64Processing.encodeData(CitizenCardInterface.getCertificate());

				String[] subjectNameArray = CitizenCardInterface.getFirstLastName();
				String subjectName = subjectNameArray[0]+" "+subjectNameArray[1];

				String insertedName = firstName+" "+lastName;

				if(subjectName.compareToIgnoreCase(insertedName)!= 0){
					JOptionPane.showMessageDialog(this, "O nome introduzido é diferente do mome do Cartão inserido"+
							"Nome Inserido:"+insertedName+" Nome Cartão:"+subjectName);
					return;
				}

			} catch (CardErrorException e) {
				JOptionPane.showMessageDialog(this, "O cartão não está inserido no leitor!!");
				return;
			}
		}
		
		PublicKey publicKey = ServerData.getServerData().getKeystoreManager().getServerPublicKey(true);
		String passHash = Hash.getStringHash(password);
		String cipheredPass = AssimEncryption.cipher(passHash, publicKey);
		
		DatabaseConnection dbConn = ServerData.getServerData().getDatabaseConnection();
		int result = dbConn.addUser(firstName, lastName, username, cipheredPass, address, certificate);
		
		if(result != 1){
			JOptionPane.showMessageDialog(this, "Não foi possível adicionar o utilizador. Provavelmente já existe outro com a mesma identificação");
			return;
		}else{
			JOptionPane.showMessageDialog(this, "Utilizador adicionado com sucesso!!");
			this.setVisible(false);
			ServerData.getServerData().getMainMenu().setVisible(true);
			this.dispose();
		}
	}

	private void cancelButtonMouseClicked(java.awt.event.MouseEvent evt) {
		this.setVisible(false);
		ServerData.getServerData().getMainMenu().setVisible(true);
		this.dispose();
		return;
	}

	/**
	 * @param args the command line arguments
	 */
	public static void main(String args[]) {
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				new AddUserWithPasswordMenu().setVisible(true);
			}
		});
	}

	//GEN-BEGIN:variables
	// Variables declaration - do not modify
	private javax.swing.JTextField _addressBox;
	private javax.swing.JButton _cancelButton;
	private javax.swing.JCheckBox _ccCertificateIncluded;
	private javax.swing.JTextField _firstNameBox;
	private javax.swing.JTextField _lastNameBox;
	private javax.swing.JButton _nextButton;
	private javax.swing.JPasswordField _passwordBox;
	private javax.swing.JPasswordField _passwordConfBox;
	private javax.swing.JTextField _usernameBox;
	private javax.swing.JLabel jLabel1;
	private javax.swing.JLabel jLabel2;
	private javax.swing.JLabel jLabel3;
	private javax.swing.JLabel jLabel4;
	private javax.swing.JLabel jLabel5;
	private javax.swing.JLabel jLabel6;
	// End of variables declaration//GEN-END:variables

}